//
//  SHUserInfoViewModel.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/28.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

class SHUserInfoViewModel: NSObject {
    
    // 数据模型
    var data: SHHomeData?
    // 认证用户图片
    var avatarImage: UIImage?
    // 会员等级图片
    var rankImage: UIImage?
    // 微博来源处理富文本
    var sourceAttr: NSAttributedString?
    // 转发数
    var repostsCountStr: String?
    // 评论数
    var commentsCountStr: String?
    // 表态数
    var attitudesCountStr: String?
    // 微博时间(只读属性 计算型)
    var sinaTimeStr: String?{
        return NSDate.sinaDate(data?.created_at ?? "")?.sinaDescriptionStr
    }
    // 原创微博富文本
    var originalContentAttr: NSMutableAttributedString?
    // 转发微博富文本
    var retweetContentAttr: NSMutableAttributedString?
    
    init(data: SHHomeData) {
        super.init()
        self.data = data
        avatarImage = getAvatarImage(data.userInfo?.verified)
        rankImage = getRankImage(data.userInfo?.mbrank)
        sourceAttr = getSourceStr(data.source)
        repostsCountStr = getSinaCount(data.reposts_count, title: "转发")
        commentsCountStr = getSinaCount(data.comments_count, title: "评论")
        attitudesCountStr = getSinaCount(data.attitudes_count, title: "赞")
        originalContentAttr = dealWithContentText(data.text)
        retweetContentAttr = dealWithContentText(data.retweeted_status?.text)
    }
}

// MARK: - 数据处理
extension SHUserInfoViewModel {
    // 认证用户图片 认证类型 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
    func getAvatarImage(verified: Int?) -> UIImage?{
        // 判读他是否为nil
        guard let _verified = verified else{
            return nil
        }
        
        switch _verified {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
    }
    // 处理会员等级图片/// 会员等级 1-6
    func getRankImage(rank: Int?) -> UIImage?{
        // 判断他是否为nil
        
        guard let _rank = rank else {
            return nil
        }
        if _rank > 0 && _rank < 7 {
            return UIImage(named: "common_icon_membership_level\(_rank)")
        }
        return UIImage(named: "common_icon_membership")
    }
}

// MARK: - 处理微博转发评论赞的业务逻辑
extension SHUserInfoViewModel {
    func getSinaCount(count: Int, title: String) -> String{
        return NSString.formatString(count, string : title)
     }
}

// MARK: - 设置'来源'文本内容
extension SHUserInfoViewModel{
    // 格式 来自 xxxx
    func getSourceStr(source: String?)-> NSAttributedString{

        let attr = NSAttributedString.stringWithFormat(data?.source, fromSubstring: "\">", toSubsting: "</", defaultString: "上海三期微博", prefix: "来自 ")
        
        return attr

    }
}

// MARK: - 处理表情字符串
extension SHUserInfoViewModel {
    /*
    上海三期[笑cry]x[笑cry]x[笑cry]x[笑cry]
    上海三期表表表表
    01 [笑cry]     chs
    02 emoticon.chs   如果相同的 emoticon
    03 通过emoticon.path  得到image  文本附件  富文本
    */
    func dealWithContentText(text: String?) -> NSMutableAttributedString? {
        // 判断是否有值
        guard let t = text else{
            return nil
        }
        // 得到一个富文本
        let allTextAttr = NSMutableAttributedString(string: t)
        // [笑cry]
        // 正则格式
        let regex = "\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]"
        // 遍历字符串
        /*
        -01 匹配的个数
        -02 匹配的结果（指针）
        -03 匹配的范围（指针）
        -04 匹配是否停止
        */
        var tempArray: [SHMatchResult] = [SHMatchResult]()
        
        (t as NSString).enumerateStringsMatchedByRegex(regex) { (count, string, range, _) -> Void in
            // 实例化一个模型
            let matchResult = SHMatchResult(string: string.memory as? String, range: range.memory)
            tempArray.append(matchResult)
        }
        // 为防止越界,倒序遍历
        for match in tempArray.reverse() {
            // 判断是否为nil
            guard let emoticon = SHEmoticonTools.sharedTools.getEmoticons(match.string) else {
                continue
            }
            // 行高
            let lineHeight = Font(15).lineHeight
            // 不可变富文本
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)
            // 替换
            allTextAttr.replaceCharactersInRange(match.range, withAttributedString: attr)
        }
        return allTextAttr
    }
}

